package ch.kerbtier.webglue;

import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;

import java.io.IOException;
import java.util.Map;

public class GroovyReloadable implements CodeRunner{
	
	private GroovyScriptEngine engine;
	
	public GroovyReloadable(String[] paths){
	    try {
	        engine = new GroovyScriptEngine(paths);
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}
	
	public Object run(String script, Map<String, Object> parameters) {
        final Binding binding = new Binding();
        
        
        for(String key:parameters.keySet()){
        	binding.setVariable(key, parameters.get(key));
        }

		binding.setVariable("script", new Object() {
			public Object evaluate(String name) {
				try {
					return engine.run(name, binding);
				} catch (ResourceException e) {
					e.printStackTrace();
				} catch (ScriptException e) {
					e.printStackTrace();
				} catch (Throwable e) {
					e.printStackTrace();
				}
				return null;
			}
		});
        
        
        try {
            return engine.run(script, binding);
        } catch (ResourceException e) {
            e.printStackTrace();
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch(Throwable e){
            e.printStackTrace();
        }
        return null;
	}
}
